﻿using Hangfire;
using LJ.Abstractions.Extensions;
using LJ.Abstractions.Pack;
using LJ.TaskScheduler.Abstractions.Attributes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJ.TaskScheduler.Hangfire.Pack;

public class TaskSchedulerHangfirePackBuilder : ITaskSchedulerHangfirePackBuilder
{
    private ConcurrentDictionary<string,TaskSchedulerWorkerInfo> WorkerInfos { get; } = [];
    private HashSet<Type> WorkerTypes { get; } = [];

    public IReadOnlyList<TaskSchedulerWorkerInfo> GetWorkerInfos()
    {
        return [.. WorkerInfos.Values];
    }
    public void Add<TTaskSchedulerWorker>() where TTaskSchedulerWorker : class, ITaskSchedulerWorker 
    {
        var workerType = typeof(TTaskSchedulerWorker);
        Add(workerType);
    }

    public void Add(Type workerType)
    {
        var taskSchedulerAttribute = workerType.GetAttribute<TaskSchedulerAttribute>();
        if (taskSchedulerAttribute == null)
        {
            return;
        }
        WorkerTypes.Add(workerType);
        var info = new TaskSchedulerWorkerInfo(taskSchedulerAttribute.Name, taskSchedulerAttribute.CronExpression, workerType);
        WorkerInfos[taskSchedulerAttribute.Name] = info;
    }
}
